package part15;

/**
 * @author wcj
 * @Date 2021/5/29 16:58
 * @Version 1.0
 */
public class Part1511 {

    public static void main(String[] args) {
        Generator<CountedObject> countedObjectGenerator = BasicGenerator.create(CountedObject.class);
        for (int i = 0; i < 5; i++) {
            System.out.println(countedObjectGenerator.next());
        }
    }
}

class CountedObject {
    private static long counter = 0;
    private final long id = counter++;

    public long id() {
        return id;
    }

    @Override
    public String toString() {
        return "CountedObject" + counter;
    }
}

/**
 * 通用生成器，可以生成任意对象，只不过生成的对象类中需要有默认构造器
 *
 * @param <T>
 */
class BasicGenerator<T> implements Generator<T> {

    private Class<T> type;

    public BasicGenerator(Class<T> type) {
        this.type = type;
    }

    @Override
    public T next() {
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> Generator<T> create(Class<T> type) {
        return new BasicGenerator<T>(type);
    }
}
